<?php

namespace action;

use artisan\db;
use artisan\http;
use artisan\input;
use core\action;
use service\file\HttpUpload;
use util\waybill\WaybillUtil;

class elesignle extends action
{

    private $api = 'http://order.core.kuaidihelp.com/v1/elesignle/';
    const WAYBILL_DB = 'orders';
    const WAYBILL_TABLE = 'tbl_elesignle_waybills';
    const PAGE_SIZE = 30;
    const UPLOAD_FILE_SAVE_PATH = ROOTPATH . 'uploads';

    public function index()
    {

    }

    /*
     * 设置申请面单账户
     * */
    public function setAccount()
    {
        if (!input::isAjaxPost()) {
            raise(1, 'file is not found!');
        }

        echo $request = $this->api . 'set/account';

        $param = [
            'account' => 'aaaa',
            'password' => 'bbb',
            'role' => 'shop',
            'role_id' => '1334',
            'role_account' => 'xzlsst@163.com',
        ];

        $response = json_decode(http::post($request, $param), true);

        print_r($response);
    }

    /**
     * addWaybill request handler
     *
     * @return void
     */
    public function addWaybills()
    {
        if (input::isPost()) {
            if ($_FILES) {
                $content_type = 'file';
            } else {
                $content_type = input::any('type');
            }
            switch ($content_type) {
                case 'interval':
                    $start = input::any('number_s');
                    $end = input::any('number_e');
                    $data = WaybillUtil::createWaybillRange($start, $end);
                    break;
                case 'input':
                    if ($waybills_str = input::any('number')) {
                        $data = WaybillUtil::strToArray($waybills_str);
                    }
                    break;
                case 'file':
                    $http_upload = new HttpUpload();
                    $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
                    if ($files = $http_upload->upload('file', static::UPLOAD_FILE_SAVE_PATH)) {
                        //compatible with output::module for json format
                        $data = $this->uploadedFileHandler($files, true);
                    }
                    !$files || !$data and $file_upload_error = $http_upload->getError();
                    break;
            }
            if (isset($data) && is_array($data)) {
                $data = array_unique($data);
                if ($this->insertToDb($data)) {
                    raise(0, '添加面单成功!');
                }
                raise(0, '添加面单失败'.db::connect(static::WAYBILL_DB)->table(static::WAYBILL_TABLE)->getLastError());
            }elseif(isset($file_upload_error)){
                raise('400',is_array($file_upload_error)?array_pop($file_upload_error):'上传发生错误');
            }
        }
        raise('400', '没有面单数据');
    }
    /**
     * getWaybills
     *
     * @return void
     */
    public function getWaybills()
    {
        //all == 0,已删除 === 1,已使用 === 2
        if (input::isAjax()) {
            $waybill_no = input::any('waybill_no');
            $type = (int) input::any('type');
            $page = (int) input::any('page');
            $page = $page > 0 ? $page : 1;
            $offset = ($page - 1) * static::PAGE_SIZE;
            $conditions = $this->buildBaseSqlData();
            $type === 1 and $conditions['is_delete'] = 'yes' or $type === 2 and $conditions['is_used'] = 'yes';
            if ($waybill_no) {
                $conditions['waybill_no like'] = $waybill_no . '%';
            }
            $model = db::connect(static::WAYBILL_DB)->table(static::WAYBILL_TABLE);
            $total_count = (int) $model->count($conditions);
            $_return = [
                'all' => $total_count,
                'total' => 0,
                'pageSize' => static::PAGE_SIZE,
                'page' => $page,
                'list' => [],
            ];
            //why reset
            if ($total_count and $data = $model->table(static::WAYBILL_TABLE)->select('waybill_no')->limit([$offset, static::PAGE_SIZE])->getAll($conditions)) {
                $_return = array_merge($_return, [
                    'total' => count($data),
                    'list' => array_column($data, 'waybill_no'),
                ]);
            }
            raise(0, '数据加载成功', $_return);
        }
        raise(400, '');
    }

    /**
     * delete a waybill number
     *
     * @return void
     */
    public function deleteWaybill()
    {
        if (input::isAjax()) {
            if ($waybill_no = input::any('waybill_no')) {
                //is soft delete or not
                //$type = input::any('type');
                $conditions = $this->buildBaseSqlData();
                $conditions['waybill_no'] = $waybill_no;
                $model = db::connect(static::WAYBILL_DB)->table(static::WAYBILL_TABLE);
                //if($return = db::connect(static::WAYBILL_DB)->table(static::WAYBILL_TABLE)->delete($conditions)){
                if ($model->count($conditions)) {
                    if ($return = $model->update($conditions, ['is_delete' => 'yes'])) {
                        raise(0, '删除成功');
                    }
                } else {
                    raise(400, '未找到对应条目!');
                }
                raise(0, '删除失败');
            }
        }
        raise(400, '');
    }

    /**
     * build common data for waybill table
     *
     * @return array
     */
    protected function buildBaseSqlData()
    {
        return [
            'brand' => $this->brand,
            'index_shop_id' => $this->index_shop_id,
            'add_by' => $this->account,
            // 'is_used' => 'no',
            // 'is_delete' => 'no',
        ];
    }

    /**
     * insertToDb
     *
     * @return integer|void
     */
    protected function insertToDb(array $data = [])
    {
        if (count($data) > 0 && !is_array(current($data))) {
            $data = WaybillUtil::buildInsertData($data, $this->buildBaseSqlData());
            if (is_array($data)  && ($sql = WaybillUtil::arrayToInsertSql($data, static::WAYBILL_TABLE, 'INSERT IGNORE'))) {
                return db::connect(static::WAYBILL_DB)->query($sql);
            }
        }
    }
    /**
     * Handler for uploaded file
     *
     * @param array $files
     * @return array
     */
    private function uploadedFileHandler(array $files, $delete_uploaded_file = false)
    {
        if (is_array($files)) {
            $file = current($files);
            if(!$file instanceof \SplFileObject){
                return [];
            }
            $file_ext = $file->getExtension();
            $data = null;
            if ($file_ext === 'txt') {
                $data = WaybillUtil::linesToArray($file);
            } elseif (in_array($file_ext, ['xlsx', 'xls', 'csv'], true)) {
                $data = WaybillUtil::parseExcelFile($file);
            } else {
                raise('400', '不支持的文件类型:' . $file_ext);
            }
            //删除上传的文件
            $delete_uploaded_file and is_file($file_path = $file->getRealPath()) and chmod($file_path, 0777) and unlink($file_path);
            if (is_array($data)) {
                return array_filter($data);
            }
        }
    }
}
